/*******************************************************************************

  Pilot Intelligence Library
    http://www.pilotintelligence.com/

  ----------------------------------------------------------------------------

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>.

*******************************************************************************/

#include "base/system/file_path/file_path.h"
#include "UART_utils.h"

namespace pi {


#if defined(PIL_WINDOWS) || defined(PIL_MINGW)

#include <windows.h>

StringArray UART_getDeviceList(void)
{
    StringArray devList;

    LPCTSTR regPath_COM = "HARDWARE\\DEVICEMAP\\SERIALCOMM\\";
    HKEY    hKey;

    LONG  Status, ret0;
    DWORD dwIndex = 0;
    CHAR  Name[64];
    DWORD dwName;
    UCHAR szPortName[64];
    DWORD Type;
    DWORD dwSizeofPortName;

    // open the regist key, if success then return ERROR_SUCCESS=0
    ret0 = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath_COM, 0, KEY_READ, &hKey);

    if( ret0 == ERROR_SUCCESS ) {
        do {
            dwName = sizeof(Name);
            dwSizeofPortName = sizeof(szPortName);

            // read the contents
            Status = RegEnumValue(hKey, dwIndex++, Name, &dwName, NULL, &Type,
                                  szPortName, &dwSizeofPortName);
            if( (Status == ERROR_SUCCESS) || (Status == ERROR_MORE_DATA) ) {
                devList.push_back((char*) szPortName);
            }
        } while( (Status == ERROR_SUCCESS) || (Status == ERROR_MORE_DATA) );

        RegCloseKey(hKey);
    }

    return devList;
}


#endif


#ifdef PIL_LINUX

inline int stringContins(const std::string& s, const std::string& p)
{
    std::string::size_type idx = s.find(p);

    if( idx != std::string::npos )
        return 1;
    else
        return 0;
}

StringArray UART_getDeviceList(void)
{
    std::string devPath = "/dev/";

    StringArray devList;
    StringArray allDev;

    // list all devices
    path_lsdir(devPath, allDev);

    // for each device
    StringArray::iterator it;
    for(it = allDev.begin(); it != allDev.end(); it++) {
        std::string& s = *it;

        if( stringContins(s, "tty") ) {
            if( stringContins(s, "USB") || stringContins(s, "ACM") ) {
                std::string devP = path_join(devPath, s);
                devList.push_back(devP);
            }
        }
    }

    return devList;
}

#endif

}
